using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Windows.Forms;
using ClientTools.Library.DataTypes.Logging;
using ClientTools.Library.Interfaces;

namespace ClientTools.Client.Controls.Logging
{
    public partial class UcLogs : BaseUserControl, IUserControl
    {
        #region Private variables
        private ILogging actLogging;
        #endregion

        public UcLogs()
        {
            InitializeComponent();
        }

        private void ResetFilter_Click(object sender, EventArgs e)
        {
            ResetFilter();
        }

        private void DeleteLog_Click(object sender, EventArgs e)
        {
            DeleteSelectedLogs();
        }

        private void DeleteSelectedLogs()
        {
            Cursor = Cursors.WaitCursor;
            var delvals = new List<int>();

            for (var i = 0; i < dgLogs.SelectedRows.Count; i++)
                delvals.Add((int)dgLogs.SelectedRows[i].Cells["ID"].Value);

            actLogging.DeleteLogsByIDs(delvals);
            GetLogs();
            Cursor = Cursors.Default;
        }

        #region GetLogs
        private void GetLogs()
        {
            Cursor = Cursors.WaitCursor;

            DateTime? startdate = null;
            DateTime? enddate = null;
            string header = null;
            int? userid = null;
            int? nodeid = null;
            string comment = null;

            int? maxrow = Decimal.ToInt32(nudMaxRows.Value);

            if (txtNodeID.Text.Trim() != "")
            {
                int x;
                if (int.TryParse(txtNodeID.Text.Trim(), out x))
                    nodeid = int.Parse(txtNodeID.Text.Trim());
                else
                {
                    MessageBox.Show("NodeID is not a number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }

            if (txtUserID.Text.Trim() != "")
            {
                int x;
                if (int.TryParse(txtUserID.Text.Trim(), out x))
                    userid = int.Parse(txtUserID.Text.Trim());
                else
                {
                    MessageBox.Show("UserID is not a number!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return;
                }
            }
            if (cboHeader.SelectedIndex != -1 && cboHeader.SelectedIndex != 0)
                header = cboHeader.SelectedItem.ToString();

            if (dtpStartdate.Checked)
                startdate = dtpStartdate.Value;

            if (dtpEnddate.Checked)
                enddate = dtpEnddate.Value;

            if (txtComment.Text.Trim() != "")
                comment = txtComment.Text.Trim();
            
            LogCollection logs;
            
            try
            {
                logs = actLogging.GetLogs(startdate, enddate, header, userid, nodeid, maxrow, comment);
            }
            catch (Exception ex)
            {
                ClearData();
                Enabled = false;
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            dgLogs.DataSource = logs;
            dgLogs.Enabled = true;
            GridViewHelper.SetDisplayColums(dgLogs, "NodeID;UserID;DateStamp;LogHeader;LogComment", true);
// ReSharper disable PossibleNullReferenceException
            dgLogs.Columns["Datestamp"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
// ReSharper restore PossibleNullReferenceException
            lblCount.Text = logs.Count.ToString();
            //if (logs.Count > 0)
                //this.dgLogs.CurrentCell = this.dgLogs.cell
                //this.dgLogs.Rows[0].Selected = true;

            Cursor = Cursors.Default;

        }

        private void GetLogs_Click(object sender, EventArgs e)
        {
            GetLogs();
        }

        private void MaxRows_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                GetLogs();
        }

        private void UserIdKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                GetLogs();
        }

        private void NodeIdKeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                GetLogs();
        }

        private void Header_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetLogs();
        }

        private void Comment_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Enter)
                GetLogs();
        }
        #endregion

        #region I_UserControl Member

        public void SetData(Library.Settings.Profile profile)
        {
            ActProfile = profile;
            ActProfile.InitProvider();
            ActProvider = ActProfile.ProviderObject;

            if (!ImplementsLogging())
            {
                Enabled = false;
                return;
            }

            actLogging = (ILogging)ActProvider;
            ClearData();
            Enabled = true;
            GetLogHeaders();
        }

        public string Header
        {
            get { return "Logging"; }
        }

        public int Sort
        {
            get { return 1; }
        }

        public bool ShowDelimiter
        {
            get { return true; }
        }

        public Image ButtonImage
        {
            get { return tsbLogViewer.Image; }
        }

        public string ButtonText
        {
            get { return "LogViewer"; }
        }

        #endregion

        public void ClearData()
        {
            dgLogs.DataSource = null;
            dgLogs.Enabled = false;
        }

        private void GetLogHeaders()
        {
            Cursor = Cursors.WaitCursor;
            LogInfoCollection loginfos;
            try
            {
                loginfos = actLogging.GetLogInfos();
            }
            catch (Exception ex)
            {
                ClearData();
                Enabled = false;
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            cboHeader.Items.Clear();
            if (loginfos != null)
            {
                cboHeader.Items.Add(">> Select a header <<");
                foreach (var li in loginfos)
                    cboHeader.Items.Add(li.LogHeader);
                cboHeader.SelectedIndex = 0;
            }
            Cursor = Cursors.Default;
        }

        private void UcLogsLoad(object sender, EventArgs e)
        {
            GridViewHelper.SetGridLayout(dgLogs);
        }

        private void ResetFilter()
        {
            txtNodeID.Text = "";
            txtUserID.Text = "";
            txtComment.Text = "";
            cboHeader.SelectedIndex = 0;

            nudMaxRows.Value = 100;

            dtpEnddate.Value = DateTime.Now;
            dtpStartdate.Value = DateTime.Now;
            dtpEnddate.Checked = false;
            dtpStartdate.Checked = false;
        }

        private void CmdClearLogsByDateClick(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            actLogging.DeleteLogsByDate(DateTimePicker1.Value);
            GetLogInfos();
            Cursor = Cursors.Default;
        }

        private void CmdClearLogsByHeaderClick(object sender, EventArgs e)
        {
            if (cboHeader.SelectedItem == null)
            {
                MessageBox.Show("No header selected!", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            Cursor = Cursors.WaitCursor;
            try
            {
                actLogging.DeleteLogsByHeader((string)cboHeader.SelectedItem);
            }
            catch (Exception ex)
            {
                ClearData();
                Enabled = false;
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            GetLogInfos();
            Cursor = Cursors.Default;
        }

        private void GetLogInfos()
        {
            LogInfoCollection loginfos;
            try
            {
                loginfos = actLogging.GetLogInfos();
            }
            catch (Exception ex)
            {
                ClearData();
                Enabled = false;
                Cursor = Cursors.Default;
                MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }

            comboBox1.Items.Clear();
            lvLogInfos.Items.Clear();
            if (loginfos != null)
            {
                foreach (LogInfo li in loginfos)
                {
                    comboBox1.Items.Add(li.LogHeader);
                    var lv = new ListViewItem(li.LogHeader + " (" + li.Count + ")");
                    lvLogInfos.Items.Add(lv.Text);
                    lv.Tag = li;
                }
                pnlContent.Enabled = true;
                lblSum.Text = "Sum: " + loginfos.Count;
                cboHeader.SelectedIndex = 0;
            }

        }

        private void GetLogInfos_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            GetLogInfos();
            Cursor = Cursors.Default;
        }

        private void ContextMenuStrip1_Opening(object sender, CancelEventArgs e)
        {
            if (dgLogs.Rows.Count == 0 || dgLogs.SelectedRows.Count != 1)
                e.Cancel = true;
        }

        private void CopyCommentToClipboardToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Clipboard.SetText((string)dgLogs.SelectedRows[0].Cells["LogComment"].Value);
        }

        private void Logs_KeyUp(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Delete)
                DeleteSelectedLogs();
        }

    }
}
